import Vue from 'vue'
import App from '@/App.vue'
import router, { routesAll, whiteListMenu, menus } from '@/router/index'
import store from './store'
import '@/styles/normalize.css'
import '@/styles/reset.css'
import { formateRouteConfig, setMenuList } from '@utils/AccessControl'
import { urlParse } from '@/utils/tools'
import config from '@/config/index'
import filters from '@/filters/index'
import http from '@/api/index'

import { AJAX } from '@/utils/request'
import './plugins/element.js'

Vue.config.productionTip = false

Vue.prototype.$http = http
const { hideMenus = '' } = urlParse(window.location.href).param
store.commit('setHideMenus', hideMenus) // 记录路由

/**
 * 路由前置守卫，权限校验
 */
router.beforeEach(async (to, from, next) => {
    // 路由初始化后
    if (!!store.state.app.routesList && to.matched.length > 0) {
        next()
    } else {
        // 权限校验、菜单权限未开启则读取默认菜单及路由配置
        if (config.bspFlag) {
            if (!config.menuFlag) {
                store.commit('setMenuList', JSON.parse(JSON.stringify(menus))) // 生成菜单列表并展示
                store.commit('setRoutesList', routesAll) // 记录路由
                router.addRoutes(routesAll) // 添加路由
                next({ ...to, replace: true })
                return false
            }
        } else {
            store.commit('setMenuList', JSON.parse(JSON.stringify(menus))) // 生成菜单列表并展示
            store.commit('setRoutesList', routesAll) // 记录路由
            router.addRoutes(routesAll) // 添加路由
            next({ ...to, replace: true })
            return false
        }

        // 开启权限校验及菜单校验时--执行
        const form = {
            systemCode: config.systemCode,
        }
        // 请求权限菜单
        const res = await AJAX.post(config.menusURL, form)
        const bspData = res.data.entries || []
        store.commit('setMenuList', setMenuList(bspData)) // 生成菜单列表并展示
        const { routeAll, bspRoute } = formateRouteConfig(bspData, routesAll, whiteListMenu) // 根据bsp匹配路由
        store.commit('setRoutesList', routeAll) // 记录路由
        router.addRoutes(routeAll) // 添加路由
        // 如果访问不带路由的地址重定向到路由列表第一个，否则重定向到当前路径,且只在bsp返回的菜单中查找，不包含白名单中路由
        const initPath = bspRoute.find(item => {
            return !!item.path && item.path !== '/*'
        })
        if (to.path === '/') {
            next({ path: initPath ? initPath.path : '/403', replace: true })
        } else {
            next({ ...to, replace: true })
        }
    }
})

// 全局过滤器
Object.keys(filters).forEach(filterName => {
    Vue.filter(filterName, filters[filterName])
})

new Vue({
    router,
    store,
    render: h => h(App),
}).$mount('#app')
